<template>
  <div class="app-container">
    <!-- 原材料质量管理 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
            <el-form-item label="批次号" prop="code">
              <el-input
                v-noSpace
                v-model="queryParams.code"
                placeholder="请输入批次号"
                class="!w-[192px]"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="生产批次号" prop="parentCode">
              <el-input
                v-noSpace
                v-model="queryParams.parentCode"
                class="!w-[192px]"
                placeholder="请输入生产批次号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="产品类型" prop="productCategory">
              <el-select
                v-model="queryParams.productCategory"
                placeholder="请选择产品类型"
                class="!w-[192px]"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in materialTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-noSpace
                v-model="queryParams.productName"
                placeholder="请输入产品名称"
                class="!w-[192px]"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="质检人员" prop="reportName">
              <el-input
                v-noSpace
                v-model="queryParams.reportName"
                placeholder="请输入质检人员"
                class="!w-[192px]"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                @change="handleQuery"
                clearable
                class="!w-[192px]"
              >
                <el-option
                  v-for="item in seleteTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="检验时间" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="daterange"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
                @change="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button type="primary" icon="search" @click="handleQuery">查询</el-button>
              <el-button
                icon="plus"
                type="warning"
                @click="handleEdit('add', {})"
                v-hasPerm="'sys:productQuality:edit'"
              >
                新增
              </el-button>
              <el-button type="primary" @click="downloadTable" v-hasPerm="'sys:productQuality:exp'">
                导出
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table id="educe-table" v-loading="loading" :data="tabData">
            <el-table-column prop="code" label="批次号" align="center" />
            <el-table-column prop="parentCode" label="生产批次号" align="center" width="150" />
            <el-table-column prop="productCategory" label="产品类型" align="center">
              <template #default="scope">
                <div>{{ productCategoryFormat(scope.row.productCategory) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称/编号" align="center" width="150">
              <template #default="scope">
                <div>{{ scope.row.productName + "/" + scope.row.productCode }}</div>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="supplier" label="抽检筐码" align="center" /> -->
            <!-- <el-table-column prop="purchaseQuantity" label="采购数量" align="center" /> -->
            <el-table-column prop="actualQuantity" label="实际产量" align="center" width="150">
              <template #default="scope">
                <div>
                  {{ scope.row.actualQuantity }}
                  {{ unitFormat(scope.row.unit) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedQuantity" label="合格数量" align="center" width="150">
              <template #default="scope">
                <div>
                  {{ scope.row.qualifiedQuantity }}
                  {{ unitFormat(scope.row.unit) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="qualifiedRate"
              label="合格率"
              align="center"
              :formatter="qualifiedQuantityFormatter"
            />
            <el-table-column prop="status" label="状态" align="center">
              <template #default="scope">
                <div>{{ stateFormatter(scope.row.status) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="reportName" label="质检人员" align="center" />
            <el-table-column prop="reportTime" label="质检时间" align="center" />
            <el-table-column label="操作" width="250" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" link @click="handleEdit('look', scope.row)">查看</el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit('edit', scope.row)"
                  v-hasPerm="'sys:productQuality:edit'"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  link
                  @click="handleDelete(scope.$index, scope.row)"
                  v-hasPerm="'sys:productQuality:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      class="df"
      @close="dialogClose"
    >
      <el-form
        ref="dialogFormRef"
        :model="paramsInfo"
        :inline="true"
        label-width="130px"
        :rules="rules"
        :disabled="dialog.title === '查看' ? true : false"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产批次号" prop="parentCode">
              <el-select
                v-model="paramsInfo.parentCode"
                placeholder="请选择生产批次号"
                style="width: 192px"
                @change="purchasChange"
                filterable
              >
                <el-option
                  v-for="item in purchasList"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
              <!-- <el-input v-noSpace
                v-model="paramsInfo.parentCode"
                placeholder="请输入生产批次号"
                clearable
                maxlength="100"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productCategory">
              <el-select
                v-model="paramsInfo.productCategory"
                placeholder="请选择产品类型"
                style="width: 192px"
              >
                <el-option
                  v-for="item in materialTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-noSpace
                disabled
                v-model="paramsInfo.productCode"
                placeholder="请输入产品编号"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-noSpace
                disabled
                v-model="paramsInfo.productName"
                placeholder="请输入产品名称"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="供应商编号" prop="supplierCode">
              <el-input v-noSpace
                v-model="paramsInfo.supplierCode"
                placeholder="请输入供应商编号"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-noSpace
                v-model="paramsInfo.supplierName"
                placeholder="请输入供应商名称"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="12">
            <el-form-item label="采购数量" prop="purchaseQuantity">
              <el-input v-noSpace
                v-model.number="paramsInfo.purchaseQuantity"
                placeholder="请输入采购数量"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item :label="`实际数量（${unitValue?.label || ''}）`" prop="actual_quantity">
              <el-input
                v-noSpace
                disabled
                v-model.number="paramsInfo.actualQuantity"
                placeholder="请输入实际数量"
                clearable
                maxlength="100"
                @input="computeRate"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="`合格数量（${unitValue?.label || ''}）`"
              prop="qualified_quantity"
            >
              <el-input
                v-noSpace
                v-model.number="paramsInfo.qualifiedQuantity"
                placeholder="请输入合格数量"
                clearable
                maxlength="100"
                @input="computeRate"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="合格率" prop="qualified_rate">
              <el-input
                v-noSpace
                v-model="qualifiedRate"
                disabled
                placeholder="请输入合格率"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检状态" prop="status">
              <el-select
                v-model="paramsInfo.status"
                placeholder="请选择质检状态"
                style="width: 192px"
              >
                <el-option
                  v-for="item in statesList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="实物图片" prop="physicalImage">
              <FileUpload
                v-model="paramsInfo.physicalImage"
                :showUploadBtn="dialog.title === '查看' ? false : true"
                :showDelBtn="dialog.title === '查看' ? false : true"
                :data="{ bizType: 'contract' }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="报告图片" prop="reportImage">
              <!-- <MultiImageUpload v-model="paramsInfo.qualityImg" :data="{ bizType: 'contract' }" /> -->
              <!-- <FileUpload
                v-model:model-value="paramsInfo.qualityImg"
                uploadBtnText="点击上传"
                :showTip="true"
                :data="{ bizType: 'contract' }"
                :maxSize="5* 1024 * 1024"
                @update:modelValue="handleUpdateFileInfoJson(paramsInfo.qualityImg, 'qualityImg')"
                :showFileList="false"
              ></FileUpload> -->
              <FileUpload
                v-model="paramsInfo.reportImage"
                :showUploadBtn="dialog.title === '查看' ? false : true"
                :showDelBtn="dialog.title === '查看' ? false : true"
                :data="{ bizType: 'contract' }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="质检人" prop="reportName">
              <el-input
                v-noSpace
                v-model="paramsInfo.reportName"
                placeholder="请输入质检人"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="质检时间" prop="reportTime">
              <el-date-picker
                v-model="paramsInfo.reportTime"
                placeholder="请输入质检时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
              <!-- <el-input v-noSpace
                v-model="paramsInfo.reportTime"
                placeholder="请输入质检时间"
                clearable
                maxlength="100"
              /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button
            v-if="dialog.title !== '查看' ? true : false"
            v-debounce="submitDialog"
            type="primary"
          >
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import * as XLSX from "xlsx-js-style";
import qualityAPI, {
  QualityControlInquire,
  QualityControlInfo,
  QualityControlTab,
} from "@/api/quality/quality";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";
import prodOrderManageApi from "@/api/prodManage/prodOrderManage";
import PurchasApi, { PurchasPageQuery } from "@/api/order/purchas";
defineOptions({
  name: "User",
  inheritAttrs: false,
});
const qualifiedRate = ref("");
const queryFormRef = ref(ElForm);
// 搜索查询
const queryParams = reactive<QualityControlInquire>({
  pageNum: 1,
  pageSize: 10,
  qualityType: 0,
});
// 表单数据
const paramsInfo = reactive<QualityControlInfo>({});
// 表格数据
const tabData = ref<QualityControlTab[]>();
const selectedMonthDate = ref(new Date().toISOString().slice(0, 7));
const materialTypes = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getProduct = () => {
  configApi
    .getTypePage({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      materialTypes.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};
const productCategoryFormat = (productCategory: string) => {
  return materialTypes.value.find((item: any) => item.value == productCategory)?.label;
};
const seleteTypes = [
  { value: 0, label: "待检验" },
  { value: 1, label: "检验中" },
  { value: 2, label: "检验通过" },
  { value: 3, label: "检验不通过" },
];

const dialog = reactive({
  title: "",
  visible: false,
  type: "",
});
const statesList = ref([
  {
    label: "待检验",
    value: 0,
  },
  {
    label: "检验中",
    value: 1,
  },
  {
    label: "检验通过",
    value: 2,
  },
  {
    label: "检验不通过",
    value: 3,
  },
]);

const rules = reactive<Record<string, FormItemRule[]>>({
  parentCode: [{ required: true, message: "采购订单是必填项", trigger: "blur" }],
  productCategory: [{ required: true, message: "原材料类型是必填项", trigger: "blur" }],
  productCode: [{ required: true, message: "原材料编号是必填项", trigger: "blur" }],
  // stepName: [{ required: true, message: "作业顺序是必填项", trigger: "blur" }],
  // qualityName: [{ required: true, message: "品质要求是必填项", trigger: "blur" }],
  // toolName: [{ required: true, message: "工具用品是必填项", trigger: "blur" }],
});

const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);
const subDisabled = ref(false);
const dialogFormRef = ref(ElForm);

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
function handleQuery() {
  loading.value = true;

  qualityAPI
    .getPage(queryParams)
    .then((data) => {
      console.log(data);
      tabData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 合计
function handleTotal() {
  // loading.value = true;
  // console.log("queryParams", queryParams);
  // qualityAPI
  //   .getTotal(queryParams)
  //   .then((data) => {
  //     console.log("data", data);
  //     listTotal.value = data?.qtyTotal ?? 0;
  //     // pageData.value = [...(data?.list as any)];
  //     // total.value = data.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
}
//合格率计算
function computeRate() {
  console.log(paramsInfo.actualQuantity);
  if (!paramsInfo.actualQuantity) return;
  if (!paramsInfo.qualifiedQuantity) return;
  // if(paramsInfo.actual_quantity<paramsInfo.qualified_quantity)

  let rate = Math.round((paramsInfo.qualifiedQuantity / paramsInfo.actualQuantity) * 100);

  function clampToPercentage(value: number) {
    return Math.min(Math.max(value, 0), 100);
  }
  let clampedValue = clampToPercentage(rate);
  console.log(clampedValue + "%"); // 输出 100%
  qualifiedRate.value = clampedValue + "%";
  paramsInfo.qualifiedRate = clampedValue;
  // return clampedValue+"%"
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;

  handleQuery();
}

function handleView(index: any, row: any) {
  // 查看操作的逻辑
  console.log("查看", index, row);
}
function imgFormatter(img: string) {
  let data;
  if (typeof img === "string") {
    data = img.split(",").map((url: any) => {
      const name = url.split("/").pop(); // 提取文件名
      return { name, url };
    });
  }
  return data;
}
function clearDialogFormData() {
  let data = {
    productCategory: "", // 原材料类型  产品类型
    productCode: "", // 原材料编号  产品编号
    productName: "", // 原材料名称  产品名称
    supplierCode: "", // 供应商编号
    supplierName: "", // 供应商名称
    purchaseQuantity: "", // 采购数量
    actualQuantity: "", // 实际数量
    qualifiedQuantity: "", // 合格数量
    qualifiedRate: "", //合格率
    physicalImage: [], //实物图
    reportImage: [], //报告图
    parentCode: "", //生产单号 采购单号 生产批次号
    code: "", //质检单号 批次号
    reportName: "", //质检人
    reportTime: "", //质检时间
    orderType: "", //订单类型, 0=生产单号, 1=采购单号
    qualityType: "", //质检单类型, 0=产品质检单, 1=原材料质检单
    remark: "", //备注
    id: "",
    status: "",
  };
  Object.assign(paramsInfo, { ...data });
}
const purchasChange = (row: any) => {
  console.log(row, "actualQuantity");
  paramsInfo.parentCode = row.value;
  paramsInfo.productCode = row.productCode;
  paramsInfo.productName = row.productName;
  paramsInfo.actualQuantity = row.actualQuantity;
  // cons;
  if (row.unit) {
    unitValue.value = unitOptions.value.find(
      (item) => item.value === row.unit.toLowerCase()
    ) as any;
  }
};
function handleEdit(type: any, row: any) {
  // 编辑操作的逻辑
  console.log("编辑", type, row);
  dialog.visible = true;
  subDisabled.value = false;
  qualifiedRate.value = "";
  let upData = { ...row };
  if (type === "add") {
    dialog.title = "新增";
    clearDialogFormData();
  } else {
    if (row.physicalImage) {
      upData.physicalImage = row.physicalImage.map((item: any) => {
        return {
          name: item.split("/").pop(),
          url: item,
        };
      });
    } else {
      upData.physicalImage = [];
    }
    if (row.reportImage) {
      upData.reportImage = row.reportImage.map((item: any) => {
        return {
          name: item.split("/").pop(),
          url: item,
        };
      });
    } else {
      upData.reportImage = [];
    }
    if (row.qualifiedRate) {
      qualifiedRate.value = row.qualifiedRate + "%";
    }
    if (type === "edit") {
      dialog.title = "编辑";
    } else {
      dialog.title = "查看";
      subDisabled.value = true;
    }
  }
  if (upData.unit) {
    unitValue.value = unitOptions.value.find(
      (item) => item.value === upData.unit.toLowerCase()
    ) as any;
  } else {
    let unit = purchasList.value.find((item: any) => item.value === upData.productCode)?.unit;
    unitValue.value = unitOptions.value.find((item) => item.value === unit.toLowerCase()) as any;
  }

  Object.assign(paramsInfo, upData);
}
function handleDelete(index: any, row: any) {
  // 删除操作的逻辑
  console.log("删除", index, row.id);
  qualityAPI
    .delProdReport({ id: row.id })
    .then((data) => {
      ElMessage.success("操作成功");
      dialog.visible = false;
      handleQuery();
      // clearDialogFormData();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}
//下载表格
const downloadTable = () => {
  const table = document.getElementById("educe-table") as HTMLTableElement;
  console.log(table);
  if (table) {
    const ws = XLSX.utils.table_to_sheet(table);
    ws["!cols"] = [
      { wch: 40 },
      { wch: 40 },
      { wch: 10 },
      { wch: 20 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      // { wch: 10 },
      { wch: 0, hidden: true }, // 列宽，隐藏
    ];
    const wb = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, ws, "质检单表");
    XLSX.writeFile(wb, `质检单表_${selectedMonthDate.value}.xlsx`);
  } else {
    ElMessage.error("表格未找到");
  }
};

function qualifiedQuantityFormatter(row: any, column: any, cellValue: any) {
  return `${cellValue ? cellValue : 0}%`;
}
function stateFormatter(states: number) {
  let state = "";
  switch (states) {
    case 1:
      state = "检验中"; // 当表达式的结果等于 value1 时，则执行该代码
      break;
    case 2:
      state = "检验通过"; // 当表达式的结果等于 value2 时，则执行该代码
      break;
    case 3:
      state = "检验不通过"; // 当表达式的结果等于 valueN 时，则执行该代码
      break;
    default:
      state = "待检验"; // 如果没有与表达式相同的值，则执行该代码
  }
  return state;
}
function dialogClose() {
  dialog.visible = false;
  unitValue.value = {};
}
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 提交弹窗
function submitDialog() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    let paramsData = {};
    console.log(paramsInfo);
    // console.log(paramsInfo.reportImage);
    let data = JSON.parse(JSON.stringify(paramsInfo));
    console.log(data);
    if (data?.reportImage) {
      data.reportImage = data?.reportImage.map((item: any) => item.url);
    }
    if (data?.physicalImage) {
      data.physicalImage = data?.physicalImage.map((item: any) => item.url);
    }

    data.remark = "";
    data.orderType = 0; //采购订单
    data.qualityType = 0; //原材料质检单
    data.unit = unitValue.value.value;
    paramsData = { ...data };
    console.log(paramsData);
    qualityAPI
      .saveOrUpdateProdReport(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
        // clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}
let purchasList: any;
const purchasParams = reactive<PurchasPageQuery>({
  pageNum: 1,
  pageSize: 999,
});
// 查询生产批次号
function getpurchas() {
  let data = {
    pageNum: 1,
    pageSize: 999,
  };
  prodOrderManageApi
    .getPage(data)
    .then((data) => {
      console.log(data, "data");
      let list = data?.list.map((item: any) => {
        return {
          label: item.code,
          value: item.code,
          productCode: item.productCode,
          productName: item.productName,
          actualQuantity: item.qty,
          unit: item.unit,
        };
      });

      purchasList = list;
      console.log(purchasList);
    })
    .finally(() => {});
}
onMounted(() => {
  handleQuery();
  getpurchas();
  getProduct();
  getUnitList();
  // handleTotal();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
